/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.aop.service.BisLogService;
import me.zhengjie.base.OrgWeightVo;
import me.zhengjie.base.WeightVo;
import me.zhengjie.business.domain.*;
import me.zhengjie.business.domain.sup.Gsgl;
import me.zhengjie.business.domain.sup.Rygl;
import me.zhengjie.business.domain.vo.DqyVo;
import me.zhengjie.business.domain.vo.HljgDspVo;
import me.zhengjie.business.domain.vo.ZhgkQyVo;
import me.zhengjie.business.domain.vo.ZhgkZpbhVo;
import me.zhengjie.business.repository.*;
import me.zhengjie.business.service.ZhsqHistoryService;
import me.zhengjie.business.service.dto.SbgsDto;
import me.zhengjie.business.service.dto.SbgsQueryCriteria;
import me.zhengjie.business.service.mapstruct.AdlZhsqMapper;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.inter.service.MpMsgService;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.domain.vo.GsglScale;
import me.zhengjie.modules.system.repository.GsglScaleRepository;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.repository.LocalStorageRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.business.service.ZhsqService;
import me.zhengjie.business.service.dto.ZhsqDto;
import me.zhengjie.business.service.dto.ZhsqQueryCriteria;
import me.zhengjie.business.service.mapstruct.ZhsqMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xiahongbo
* @date 2022-04-15
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class ZhsqServiceImpl implements ZhsqService {

    private final FpryRepository fpryRepository;
    private final RyglRepository ryglRepository;
    private final ZhsqRepository zhsqRepository;
    private final ZhsqCyRepository zhsqCyRepository;
    private final HljgRepository hljgRepository;
    private final GsglRepository gsglRepository;
    private final GsRepository gsRepository;
    private final ZhsqMapper zhsqMapper;
    private final DictDetailService dictDetailService;
    private final GsglScaleRepository gsglScaleRepository;

    private final LocalStorageRepository localStorageRepository;
    private final AdlZhsqRepository adlZhsqRepository;
    private final AdlZhsqMapper adlZhsqMapper;
    private final ZhsqHistoryRepository zhsqHistoryRepository;
    private final MpMsgService mpMsgService;
    private final UserService userService;
    private final ZhsqHistoryService zhsqHistoryService;
    private final OrderRepository orderRepository;

    @PersistenceContext
    private EntityManager em;

    @Override
    public Page<Zhsq> queryAll(ZhsqQueryCriteria criteria, Pageable pageable){
        Page<Zhsq> page = zhsqRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return page;
    }

    @Override
    public List<ZhsqDto> queryAll(ZhsqQueryCriteria criteria){
        return zhsqMapper.toDto(zhsqRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public Object querySelfAssess(String name, String sbgsId, int[] startEnd) {
        // 使用预编译防止sql注入
        String sql = "select r1.* from bis_zhsq r1 " +
                "left join bis_gsgl r2 on r1.bis_zhsq_hljg_id = r2.bis_gsgl_id " +
                "left join bis_hljg_tcqh r3 on r1.bis_zhsq_snry_ybssqx=r3.tcqh_id and r1.bis_zhsq_hljg_id=r3.hljg_id " +
                "where r2.bis_gsgl_sbgs_id = :sbgsId " +
                "and r1.BIS_ZHSQ_ZT='04' " +
                "and r3.hljg_id is not null";
        Query query = em.createNativeQuery(sql);
        query.setFirstResult(startEnd[0]);
        query.setMaxResults(startEnd[1] - startEnd[0]);
        query.setParameter("sbgsId", sbgsId);
        List result = query.getResultList();
        List<ZhsqDto> zhsqDtos = new ArrayList<>();
        for (Object obj : result) {
            Object[] arr = (Object[]) obj;

            ZhsqDto zhsqDto = new ZhsqDto();
            zhsqDto.setBisZhsqId(Long.parseLong(arr[0].toString()));
            zhsqDto.setBisZhsqSnryId((String)arr[2]);
            zhsqDto.setBisZhsqSnryXm((String)arr[3]);
            zhsqDto.setBisZhsqSnryXb((String)arr[4]);
            zhsqDto.setBisZhsqSnrySfz((String)arr[5]);
            zhsqDto.setBisZhsqSnryYbssqx((String)arr[6]);
            zhsqDto.setBisZhsqAdl((String)arr[10]);
            zhsqDto.setBisZhsqZt((String)arr[11]);
            zhsqDto.setBisZhsqNl((String)arr[28]);
            zhsqDto.setBisZhsqLxdh((String)arr[29]);
            zhsqDto.setBisZhsqHldzSsqx((String)arr[30]);
            zhsqDto.setBisZhsqHldzXxdz((String)arr[31]);
            zhsqDto.setBisZhsqHldz((String)arr[32]);
            zhsqDto.setBisZhsqJhrxm((String)arr[33]);
            zhsqDto.setBisZhsqJhrdh((String)arr[34]);
            zhsqDto.setBisZhsqGx((String)arr[35]);
            zhsqDto.setBisZhsqSqyy((String)arr[36]);
            zhsqDto.setBisZhsqYbkh((String)arr[37]);
            zhsqDto.setBisZhsqCbzt((String)arr[38]);

            zhsqDtos.add(zhsqDto);
        }
        String countSql = "select count(*) from bis_zhsq r1 " +
                "left join bis_gsgl r2 on r1.bis_zhsq_hljg_id = r2.bis_gsgl_id " +
                "left join bis_hljg_tcqh r3 on r1.bis_zhsq_snry_ybssqx=r3.tcqh_id and r1.bis_zhsq_hljg_id=r3.hljg_id " +
                "where r2.bis_gsgl_sbgs_id = :sbgsId " +
                "and r1.BIS_ZHSQ_ZT='04' " +
                "and r3.hljg_id is not null";
        Query queryCount = em.createNativeQuery(countSql);
        queryCount.setParameter("sbgsId", sbgsId);
        Object totalElements = queryCount.getSingleResult();
        Map<String,Object> m = PageUtil.toPage(zhsqDtos, totalElements);
        return m;
    }

    @Override
    @Transactional
    public ZhsqDto findById(Long bisZhsqId) {
        Zhsq zhsq = zhsqRepository.findById(bisZhsqId).orElseGet(Zhsq::new);
        ValidationUtil.isNull(zhsq.getBisZhsqId(),"Zhsq","bisZhsqId",bisZhsqId);
        return zhsqMapper.toDto(zhsq);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZhsqDto create(Zhsq resources, String ids) {
        log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 start");
        log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 新增照护图片：{} ", ids);
        Gsgl gsgl = gsglRepository.queryGsgl(SecurityUtils.getCurrentUserId());
        Hljg hljg = hljgRepository.findById(gsgl.getBisGsglId()).orElseGet(Hljg::new);
        //resources.setBisZhsqId(IdUtil.simpleUUID());
        resources.setHljg(hljg);
        resources.setBisZhsqHljgBm(hljg.getBisGsglYljgdm());

        String pggsId = hljg.getPggs() == null ? "" : hljg.getPggs().getBisGsglId();
        String sbgsId = hljg.getSbgs() == null ? "" : hljg.getSbgs().getBisGsglId();
        String pggsName = hljg.getPggs() == null ? "" : hljg.getPggs().getBisGsglQymc();
        String sbgsName = hljg.getSbgs() == null ? "" : hljg.getSbgs().getBisGsglQymc();

        // 判断护理机构是否存在评估公司
        if(StringUtils.isEmpty(pggsId) && StringUtils.isEmpty(sbgsId)) {



        } else if(StringUtils.isEmpty(pggsId)) {
            log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 评估公司为空，商保公司代为评估：{} ", sbgsName);
            resources.setBisSbgsId(sbgsId);
            resources.setBisPggsId(sbgsId);
        } else {
            log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 评估公司不为空，商保公司复核：{}，评估公司评估：{} ", sbgsName, pggsName);
            resources.setBisSbgsId(sbgsId);
            resources.setBisPggsId(pggsId);
        }
        String fs = resources.getBisZhsqAdl();
        log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 保存ADL量表评分 - {}", fs);

        Map<String, String> snMap = GetSndj.analyse(Integer.parseInt(fs), Integer.parseInt(resources.getBisZhsqNl()));

        String sndj = snMap.get(GetSndj.SNDJ);
        String dyqx = snMap.get(GetSndj.DYQX);

        log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 失能等级 - {}", sndj);
        log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 待遇期限 - {}", dyqx + "个月");
        resources.setBisZhsqSndj(sndj);
        Date dykkrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateTimeUtil.getNow(), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
        if("85周岁以上".equals(sndj) || "90周岁以上".equals(sndj)) {

            Date dyjsrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateUtil.endOfYear(new Date()), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
            log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 85周岁以上，待遇期为年末最后一天");
            log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 待遇开始日期：{}，待遇结束日期：{} ", dyjsrq, dyjsrq);
            int months = DateTimeUtil.diffMonths(dyjsrq, dykkrq);
            months = months == 0 ? 1 : months;
            resources.setBisZhsqDykkrq(dykkrq);
            resources.setBisZhsqDyjsrq(dyjsrq);
            resources.setBisZhsqXsdyq(months+"个月");
        } else {
            Date tempDate = DateTimeUtil.addMonths(dykkrq, Integer.parseInt(dyqx));
            Date dyjsrq = DateTimeUtil.addDays(tempDate, -1);
            log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 待遇开始日期：{}，待遇结束日期：{} ", dyjsrq, dyjsrq);
            resources.setBisZhsqDykkrq(dykkrq);
            resources.setBisZhsqDyjsrq(dyjsrq);
            resources.setBisZhsqXsdyq(dyqx+"个月");
        }


        // 先获取实体中的ADL量表信息
        List<AdlZhsq> list = resources.getAdlZhsqs();
        // 清空实体中ADL量表信息
        resources.setAdlZhsqs(new ArrayList<>());

        int age = Integer.parseInt(resources.getBisZhsqNl());
        resources.setBisZhsqNl(String.valueOf(age));
        log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 计算年龄 {} ", age);

        log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 照护类别：入住机构护理[01] ");
        resources.setBisZhsqZhlb("01");

        resources.setBisZhsqAdlPc("402883ba943fefb7019444d38ee10002");
        // 新增adl量表
        Zhsq newZhsq = zhsqRepository.save(resources);
        Long userid = SecurityUtils.getCurrentUserId();
        for (int i = 0; i < list.size(); i++) {
            AdlZhsq adl = list.get(i);
            adl.setBisAdlZhsqId(IdUtil.simpleUUID());
            adl.setZhsq(newZhsq);
            adl.setBisUserId(userid);
            adlZhsqRepository.save(adl);
        }
        // 新增照片
        if(ids != null && !ids.equals("")){
            log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 关联附件 ");
            String[] picIds = ids.split(",");
            for (String picId:picIds) {
                Long storage_id = Long.parseLong(picId);
                LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                localStorage.setYwid(String.valueOf(newZhsq.getBisZhsqId()));
                localStorageRepository.save(localStorage);
            }
        }
        log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 end");

        return zhsqMapper.toDto(newZhsq);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZhsqDto update(Zhsq resources, String ids) {
        log.info("[ZhsqServiceImpl - update]--------------- 机构修改照护申请 start");
        // 先获取实体中的ADL量表信息
        List<AdlZhsq> list = resources.getAdlZhsqs();
        // 清空实体中ADL量表信息
        resources.setAdlZhsqs(new ArrayList<>());

        Zhsq zhsq = zhsqRepository.findById(resources.getBisZhsqId()).orElseGet(Zhsq::new);
        ValidationUtil.isNull( zhsq.getBisZhsqId(),"Zhsq","id",resources.getBisZhsqId());
        zhsq.copy(resources);
        Date lrsj = zhsq.getBisZhsqTjsj() == null ? zhsq.getLrsj() : zhsq.getBisZhsqTjsj();

        adlZhsqRepository.deleteAdlByZhid(resources.getBisZhsqId());
        Long userid = SecurityUtils.getCurrentUserId();
        for (int i = 0; i < list.size(); i++) {
            AdlZhsq adl = list.get(i);
            adl.setBisAdlZhsqId(IdUtil.simpleUUID());
            adl.setZhsq(zhsq);
            adl.setBisUserId(userid);
            adlZhsqRepository.save(adl);
        }

        String fs = resources.getBisZhsqAdl();
        log.info("[ZhsqServiceImpl - update]--------------- 机构修改照护申请 - 保存ADL量表评分 - {}", fs);

        Map<String, String> snMap = GetSndj.analyse(Integer.parseInt(fs), Integer.parseInt(resources.getBisZhsqNl()));

        String sndj = snMap.get(GetSndj.SNDJ);
        String dyqx = snMap.get(GetSndj.DYQX);

        log.info("[ZhsqServiceImpl - update]--------------- 机构修改照护申请 - 失能等级 - {}", sndj);
        log.info("[ZhsqServiceImpl - update]--------------- 机构修改照护申请 - 待遇期限 - {}", dyqx + "个月");
        zhsq.setBisZhsqSndj(sndj);
        Date dykkrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(lrsj, DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
        if("85周岁以上".equals(sndj) || "90周岁以上".equals(sndj)) {

            Date dyjsrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateUtil.endOfYear(new Date()), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
            log.info("[ZhsqServiceImpl - update]--------------- 机构修改照护申请 - 85周岁以上，待遇期为年末最后一天");
            log.info("[ZhsqServiceImpl - update]--------------- 机构修改照护申请 - 待遇开始日期：{}，待遇结束日期：{} ", dyjsrq, dyjsrq);
            int months = DateTimeUtil.diffMonths(dyjsrq, dykkrq);
            months = months == 0 ? 1 : months;
            zhsq.setBisZhsqDykkrq(dykkrq);
            zhsq.setBisZhsqDyjsrq(dyjsrq);
            zhsq.setBisZhsqXsdyq(months+"个月");
        } else {
            Date tempDate = DateTimeUtil.addMonths(dykkrq, Integer.parseInt(dyqx));
            Date dyjsrq = DateTimeUtil.addDays(tempDate, -1);
            log.info("[ZhsqServiceImpl - update]--------------- 机构修改照护申请 - 待遇开始日期：{}，待遇结束日期：{} ", dyjsrq, dyjsrq);
            zhsq.setBisZhsqDykkrq(dykkrq);
            zhsq.setBisZhsqDyjsrq(dyjsrq);
            zhsq.setBisZhsqXsdyq(dyqx+"个月");
        }

        // 新增照片
        if(ids != null && !ids.equals("")){
            log.info("[ZhsqServiceImpl - update]--------------- 机构修改照护申请机构修改照护申请 - 关联附件 ");

            String[] picIds = ids.split(",");
            for (String picId:picIds) {

                Long storage_id = Long.parseLong(picId);
                LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                localStorage.setYwid(String.valueOf(resources.getBisZhsqId()));
                localStorageRepository.save(localStorage);
            }
        }

        log.info("[ZhsqServiceImpl - update]--------------- 机构修改照护申请 end");
        return zhsqMapper.toDto(zhsqRepository.save(zhsq));
    }

    /**
     * 提交机构照护申请
     * 存在先新增，再提交的情况
     * @param resources /
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZhsqDto submitZhsq(Zhsq resources, String ids) {
        log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 start");
        if(StringUtils.isEmpty(resources.getBisZhsqId())) {  // 没有主键ID，表示新增
            log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 - 没有主键ID，表示新增");
            Gsgl gsgl = gsglRepository.queryGsgl(SecurityUtils.getCurrentUserId());
            Hljg hljg = hljgRepository.findById(gsgl.getBisGsglId()).orElseGet(Hljg::new);
            //resources.setBisZhsqId(IdUtil.simpleUUID());
            resources.setHljg(hljg);
            resources.setBisZhsqHljgBm(hljg.getBisGsglYljgdm());

            String pggsId = hljg.getPggs() == null ? "" : hljg.getPggs().getBisGsglId();
            String sbgsId = hljg.getSbgs() == null ? "" : hljg.getSbgs().getBisGsglId();
            String pggsName = hljg.getPggs() == null ? "" : hljg.getPggs().getBisGsglQymc();
            String sbgsName = hljg.getSbgs() == null ? "" : hljg.getSbgs().getBisGsglQymc();

            // 判断护理机构是否存在评估公司
            if(StringUtils.isEmpty(pggsId) && StringUtils.isEmpty(sbgsId)) {

            } else if(StringUtils.isEmpty(pggsId)) {
                log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 - 评估公司为空，商保公司代为评估：{} ", sbgsName);
                resources.setBisSbgsId(sbgsId);
                resources.setBisPggsId(sbgsId);
            } else {
                log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 - 评估公司不为空，商保公司复核：{}，评估公司评估：{} ", sbgsName, pggsName);
                resources.setBisSbgsId(sbgsId);
                resources.setBisPggsId(pggsId);
            }

            String fs = resources.getBisZhsqAdl();
            log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 - 保存ADL量表评分 - {}", fs);

            Map<String, String> snMap = GetSndj.analyse(Integer.parseInt(fs), Integer.parseInt(resources.getBisZhsqNl()));

            String sndj = snMap.get(GetSndj.SNDJ);
            String dyqx = snMap.get(GetSndj.DYQX);

            log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 - 失能等级 - {}", sndj);
            log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 - 待遇期限 - {}", dyqx + "个月");
            resources.setBisZhsqSndj(sndj);
            Date dykkrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateTimeUtil.getNow(), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
            //Date tempDate = DateTimeUtil.addMonths(dykkrq, Integer.parseInt(dyqx));
            //Date dyjsrq = DateTimeUtil.addDays(tempDate, -1);
            if("85周岁以上".equals(sndj) || "90周岁以上".equals(sndj)) {

                Date dyjsrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateUtil.endOfYear(new Date()), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
                log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 85周岁以上，待遇期为年末最后一天");
                log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 待遇开始日期：{}，待遇结束日期：{} ", dyjsrq, dyjsrq);
                int months = DateTimeUtil.diffMonths(dyjsrq, dykkrq);
                months = months == 0 ? 1 : months;
                resources.setBisZhsqDykkrq(dykkrq);
                resources.setBisZhsqDyjsrq(dyjsrq);
                resources.setBisZhsqXsdyq(months+"个月");
            } else {
                Date tempDate = DateTimeUtil.addMonths(dykkrq, Integer.parseInt(dyqx));
                Date dyjsrq = DateTimeUtil.addDays(tempDate, -1);
                log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 待遇开始日期：{}，待遇结束日期：{} ", dyjsrq, dyjsrq);
                resources.setBisZhsqDykkrq(dykkrq);
                resources.setBisZhsqDyjsrq(dyjsrq);
                resources.setBisZhsqXsdyq(dyqx+"个月");
            }

            // 先获取实体中的ADL量表信息
            List<AdlZhsq> list = resources.getAdlZhsqs();
            // 清空实体中ADL量表信息
            resources.setAdlZhsqs(new ArrayList<>());

            int age = Integer.parseInt(resources.getBisZhsqNl());
            resources.setBisZhsqNl(String.valueOf(age));
            log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 - 计算年龄 {} ", age);

            log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 - 照护类别：入住机构护理[01] ");
            resources.setBisZhsqZhlb("01");

            resources.setBisZhsqAdlPc("402883ba943fefb7019444d38ee10002");

            resources.setBisZhsqTjsj(new Date());
            log.info("resources:---------------------- {}",resources);
            // 新增adl量表
            Zhsq newZhsq = zhsqRepository.save(resources);
            Long userid = SecurityUtils.getCurrentUserId();
            for (int i = 0; i < list.size(); i++) {
                AdlZhsq adl = list.get(i);
                adl.setBisAdlZhsqId(IdUtil.simpleUUID());
                adl.setZhsq(newZhsq);
                adl.setBisUserId(userid);
                adlZhsqRepository.save(adl);
            }

            // 新增照片
            if(ids != null && !ids.equals("")){
                log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 - 关联附件 ");
                String[] picIds = ids.split(",");
                for (String picId:picIds) {
                    Long storage_id = Long.parseLong(picId);
                    LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                    localStorage.setYwid(String.valueOf(resources.getBisZhsqId()));
                    localStorageRepository.save(localStorage);
                }
            }

            if("220101".equals(newZhsq.getBisZhsqSnryYbssqx())) {
                List<OrgWeightVo> listWeight = userService.queryUserWeight(Long.parseLong(newZhsq.getBisZhsqSnryYbssqx()), "54");
                int prizeIndex = WeightUtil.getOrgWeigth(listWeight);
                OrgWeightVo prizeDto = listWeight.get(prizeIndex);
                Long userId = prizeDto.getId();
                String userName = prizeDto.getName();
                log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 - 随机分配 - 初审人员ID {}，初审人员姓名 {} ", userId, userName);

                Fpry fpry = new Fpry();
                fpry.setBisFpryId(IdUtil.simpleUUID());
                fpry.setBisFpryZhsqId(newZhsq.getBisZhsqId());
                fpry.setBisFpryRyglId(userId);
                fpry.setBisFpryRyglXm(userName);
                fpry.setBisFpryFpsj(new Date());
                fpry.setBisFpryZt("0");
                fpryRepository.save(fpry);
            }

            log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 end");
            return zhsqMapper.toDto(newZhsq);
        } else {  // 存在主键ID，表示修改
            log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 - 存在主键ID，表示修改");

            if(StringUtils.isEmpty(resources.getBisZhsqTjsj())) {

                Date currentDate = DateTimeUtil.parse(DateTimeUtil.getDate() + " 23:59:59", DateTimeUtil.DEFAULT_DATETIME_FORMAT);
                Date saveDate = resources.getLrsj();
                long diff = DateTimeUtil.diffDays(currentDate, saveDate);
                log.info("当前日期 {} ", DateTimeUtil.getDateTime(currentDate, DateTimeUtil.DEFAULT_DATE_FORMAT));
                log.info("保存日期 {} ", DateTimeUtil.getDateTime(saveDate, DateTimeUtil.DEFAULT_DATE_FORMAT));
                log.info("相差天数 {} ", diff);
                if(diff >= 4) {
                    resources.setBisZhsqTjsj(new Date());
                } else {
                    resources.setBisZhsqTjsj(saveDate);
                }
            } else {

                ZhsqHistory zhsqHistory = zhsqHistoryService.queryLastData(resources.getBisZhsqId());

                Date currentDate = DateTimeUtil.parse(DateTimeUtil.getDate() + " 23:59:59", DateTimeUtil.DEFAULT_DATETIME_FORMAT);
                Date tjDate = zhsqHistory.getLrsj();
                long diff = DateTimeUtil.diffDays(currentDate, tjDate);
                log.info("当前日期 {} ", DateTimeUtil.getDateTime(currentDate, DateTimeUtil.DEFAULT_DATE_FORMAT));
                log.info("驳回日期 {} ", DateTimeUtil.getDateTime(tjDate, DateTimeUtil.DEFAULT_DATE_FORMAT));
                log.info("相差天数 {} ", diff);
                if(diff >= 4) {
                    resources.setBisZhsqTjsj(new Date());
                }
            }
            ZhsqDto zhsqDto = this.update(resources, ids);

            if("220101".equals(zhsqDto.getBisZhsqSnryYbssqx())) {
                List<OrgWeightVo> listWeight = userService.queryUserWeight(Long.parseLong(zhsqDto.getBisZhsqSnryYbssqx()), "54");
                int prizeIndex = WeightUtil.getOrgWeigth(listWeight);
                OrgWeightVo prizeDto = listWeight.get(prizeIndex);
                Long userId = prizeDto.getId();
                String userName = prizeDto.getName();
                log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 - 随机分配 - 初审人员ID {}，初审人员姓名 {} ", userId, userName);

                Fpry fpry = new Fpry();
                fpry.setBisFpryId(IdUtil.simpleUUID());
                fpry.setBisFpryZhsqId(zhsqDto.getBisZhsqId());
                fpry.setBisFpryRyglId(userId);
                fpry.setBisFpryRyglXm(userName);
                fpry.setBisFpryFpsj(new Date());
                fpry.setBisFpryZt("0");
                fpryRepository.save(fpry);
            }

            log.info("[ZhsqServiceImpl - submitZhsq]--------------- 机构提交照护申请 end");
            return zhsqDto;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZhsqDto update(Zhsq resources) {
        log.info("update resources : {} ", resources);
        Zhsq zhsq = zhsqRepository.findById(resources.getBisZhsqId()).orElseGet(Zhsq::new);
        ValidationUtil.isNull( zhsq.getBisZhsqId(),"Zhsq","id",resources.getBisZhsqId());
        zhsq.copy(resources);

        //zhsqRepository.save(zhsq);
        return zhsqMapper.toDto(zhsqRepository.save(zhsq));
    }

    /**
     * 手机端评估居家照护
     * @param zt
     * @param id
     * @param bz
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateZhzt(String zt, Long id,String bz) {
        log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估居家照护 start");

        Zhsq zhsq = zhsqRepository.findById(id).get();
        // 先获取实体中的ADL量表信息
/*        List<Object> list = adlZhsqRepository.queryPgAdl(zhsq.getBisZhsqId());
        String[] adlIds = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            Object obj = list.get(i);
            Object[] arr = (Object[]) obj;
            adlIds[i] = (String)arr[0];
        }
        String fs = adlZhsqRepository.queryScore(adlIds);
        zhsq.setBisZhsqAdl(fs);*/

        String c1 = adlZhsqRepository.queryC1(zhsq.getBisZhsqId());
        String c2 = adlZhsqRepository.queryC2(zhsq.getBisZhsqId());
        String c3 = adlZhsqRepository.queryC3(zhsq.getBisZhsqId());
        String lastFs = c1+"/"+c2+"/"+c3;
        // adl量表自评分数
        zhsq.setBisZhsqAdl(lastFs);
        log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估机构照护 - 保存ADL量表评分 - {}", lastFs);

        Map<String, String> snMap = GetSndj.analyse(Integer.parseInt(c1),Integer.parseInt(c2),Integer.parseInt(c3), Integer.parseInt(zhsq.getBisZhsqNl()));


        String sndj = snMap.get(GetSndj.SNDJ);
        String dyqx = snMap.get(GetSndj.DYQX);
        String hjSndj = snMap.get(GetSndj.SNDJ_CODE);
        zhsq.setBisZhsqSndj(sndj);
        zhsq.setBisZhsqXsdyq(dyqx+"个月");
        zhsq.setBisZhsqHjSndj(hjSndj);

        log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估机构照护 - 失能等级 - {}", sndj);
        log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估机构照护 - 待遇期限 - {}", dyqx + "个月");
        this.update(zhsq);
        // 更新分配人员表的完成状态
        log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估居家照护 - 更新分配人员表的完成状态");
        fpryRepository.updateFpryWczt(id, DefaultUtil.RYLX_PGRY);

        ZhsqHistory zhsqHistory = new ZhsqHistory();
        zhsqHistory.setId(IdUtil.simpleUUID());
        zhsqHistory.setUserId(SecurityUtils.getCurrentUserId());
        zhsqHistory.setZhsqId(id);
        zhsqHistory.setType("02");
        zhsqHistory.setBz(bz);

        Long userId = zhsq.getBisUserId();
        UserDto user = userService.findById(userId);

        Msg msg = new Msg();
        msg.setType("WxTemplate");
        msg.setSendTime(new Timestamp(System.currentTimeMillis()));
        msg.setTarget(user.getWxOpenId());
        JSONObject content = new JSONObject();
        content.put("first","尊敬的用户，您提交的待遇申请有新的状态变动。");
        content.put("keyword1",zhsq.getBisZhsqSnryXm());
        content.put("keyword2",DateTimeUtil.getDateTime(zhsq.getLrsj(), "YYYY年MM月dd日"));
        if(zt.equals("04")){

            log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估居家照护 - 评估已通过");
            log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估居家照护 - 修改照护状态 - 04");
            zhsqRepository.updateZhzt(zt, id);
            if(sndj.indexOf("重度失能") != 0) {
                content.put("keyword3","评估已通过");
            } else {
                content.put("keyword3","评估结论为"+sndj+"，不符合居家待遇");
            }
            zhsqHistory.setResult("通过");
        }else {
            log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估居家照护 - 评估未通过");
            log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估居家照护 - 修改照护状态 - -4");
            zhsqRepository.updateZhzt(zt, id);
            log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估居家照护 - 重置照护的商保公司和评估公司");
            // zhsqRepository.updateSbgsEmpty(id);
            log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估居家照护 - ADL结果作废");
            adlZhsqRepository.updateBisZfbs(id);
            content.put("keyword3","评估未通过");
            zhsqHistory.setResult("未通过");
        }
        content.put("remark","请通过公众号查看。");
        msg.setContent(content.toJSONString());
        if(!StringUtils.isEmpty(msg.getTarget())){
            log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估居家照护 - 发送给申请人照护申请的节点状态");
            mpMsgService.create(msg);
        }

        log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估居家照护 - 记录照护审核日志");
        zhsqHistoryRepository.save(zhsqHistory);
        log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估居家照护 end");
    }


    /**
     * 手机端评估机构照护
     * @param zt
     * @param id
     * @param bz
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkPgjgzh(String zt, Long id,String bz) {
        log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 start");
        // 更新分配人员表的完成状态
        log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 更新分配人员表的完成状态");
        fpryRepository.updateFpryWczt(id, DefaultUtil.RYLX_PGRY);

        ZhsqHistory zhsqHistory = new ZhsqHistory();
        zhsqHistory.setId(IdUtil.simpleUUID());
        zhsqHistory.setUserId(SecurityUtils.getCurrentUserId());
        zhsqHistory.setZhsqId(id);
        zhsqHistory.setType("02");
        zhsqHistory.setBz(bz);

        if(zt.equals("04")){
            Zhsq zhsq = zhsqRepository.findById(id).get();
          //  log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - adl {}", zhsq.getAdlZhsqs());
            Date lrsj = zhsq.getBisZhsqTjsj();
            // 先获取实体中的ADL量表信息
/*            List<Object> list = adlZhsqRepository.queryJgPgAdl(zhsq.getBisZhsqId());
            String[] adlIds = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                Object obj = list.get(i);
                Object arr = obj;
                adlIds[i] = (String)arr;
            }
            String fs = adlZhsqRepository.queryScore(adlIds);*/
            String c1 = adlZhsqRepository.queryC1(zhsq.getBisZhsqId());
            String c2 = adlZhsqRepository.queryC2(zhsq.getBisZhsqId());
            String c3 = adlZhsqRepository.queryC3(zhsq.getBisZhsqId());
            String lastFs = c1+"/"+c2+"/"+c3;
            // adl量表自评分数
            zhsq.setBisZhsqAdl(lastFs);
            log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 保存ADL量表评分 - {}", lastFs);

            Map<String, String> snMap = GetSndj.analyse(Integer.parseInt(c1),Integer.parseInt(c2),Integer.parseInt(c3), Integer.parseInt(zhsq.getBisZhsqNl()));

            String sndj = snMap.get(GetSndj.SNDJ);
            String dyqx = snMap.get(GetSndj.DYQX);
            String hjSndj = snMap.get(GetSndj.SNDJ_CODE);

            log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 失能等级 - {}", sndj);
            log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 待遇期限 - {}", dyqx + "个月");
            zhsq.setBisZhsqSndj(sndj);
            zhsq.setBisZhsqHjSndj(hjSndj);
            Date dykkrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(lrsj, DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
            if("85周岁以上".equals(sndj) || "90周岁以上".equals(sndj)) {

                int month = DateTimeUtil.getMonth(lrsj);
                Date dyjsrq = null;

                if(month >= 10) {
                    log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 申请月份为 {}", month);
                    log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 85周岁以上，待遇期为第二年最后一天");
                    dyjsrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateUtil.endOfYear(DateTimeUtil.addMonths(lrsj, 12)), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);

                } else {
                    log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 申请月份为 {}", month);
                    log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 85周岁以上，待遇期为年末最后一天");
                    dyjsrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateUtil.endOfYear(lrsj), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);

                }

                log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 待遇开始日期：{}，待遇结束日期：{} ", dykkrq, dyjsrq);
                int months = DateTimeUtil.diffMonths(dyjsrq, dykkrq);
                months = months == 0 ? 1 : months;
                zhsq.setBisZhsqDykkrq(dykkrq);
                zhsq.setBisZhsqDyjsrq(dyjsrq);
                zhsq.setBisZhsqXsdyq(months+"个月");
            } else {
                Date tempDate = DateTimeUtil.addMonths(dykkrq, Integer.parseInt(dyqx));
                Date dyjsrq = DateTimeUtil.addDays(tempDate, -1);
                log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 待遇开始日期：{}，待遇结束日期：{} ", dykkrq, dyjsrq);
                zhsq.setBisZhsqDykkrq(dykkrq);
                zhsq.setBisZhsqDyjsrq(dyjsrq);
                zhsq.setBisZhsqXsdyq(dyqx+"个月");
            }
            this.update(zhsq);

            log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 评估已通过");
            log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 修改照护状态 - 04");
            zhsqRepository.updateZhzt("04", id);
            zhsqHistory.setResult("通过");
        }else if(zt.equals("80")) {
            log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 评估退回");
            log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 修改照护状态 - 80");
            zhsqRepository.updateZhzt("80", id);
            zhsqHistory.setResult("退回");
            log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - ADL结果作废");
            adlZhsqRepository.updateBisZfbs(id);
        }else {
            log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 评估未通过");
            log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 修改照护状态 - -4");
            zhsqRepository.updateZhzt("-4", id);
            log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - ADL结果作废");
            adlZhsqRepository.updateBisZfbs(id);
            zhsqHistory.setResult("未通过");
        }

        log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 - 记录照护审核日志");
        zhsqHistoryRepository.save(zhsqHistory);
        log.info("[ZhsqServiceImpl - checkPgjgzh]--------------- 手机端评估机构照护 end");
    }

    /**
     * 自评审批
     * @param zt
     * @param id
     * @param bz
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePcZhzt(String zt, Long id, String bz) {
        log.info("[ZhsqServiceImpl - updatePcZhzt]--------------- PC端自评审批 start");
        Zhsq zhsq = zhsqRepository.findById(id).get();

        JSONObject content = new JSONObject();
        Msg msg = new Msg();
        if("03".equals(zhsq.getBisZhsqZhlb())) {
            Long userId = zhsq.getBisUserId();
            UserDto user = userService.findById(userId);
            msg.setType("WxTemplate");
            msg.setTimes(0);
            msg.setStatus("0");
            msg.setSendTime(new Timestamp(System.currentTimeMillis()));
            msg.setTarget(user.getWxOpenId());
            content.put("first","尊敬的用户，您提交的待遇申请有新的状态变动。");
            content.put("keyword1",zhsq.getBisZhsqSnryXm());
            content.put("keyword2",DateTimeUtil.getDateTime(zhsq.getLrsj(), "YYYY年MM月dd日"));

        }

        ZhsqHistory zhsqHistory = new ZhsqHistory();
        zhsqHistory.setId(IdUtil.simpleUUID());
        zhsqHistory.setUserId(SecurityUtils.getCurrentUserId());
        zhsqHistory.setZhsqId(id);
        // 当前的状态
        zhsqHistory.setType(DefaultUtil.ZHZT_DSP);  // 11：待审批状态
        if(zt.equals(DefaultUtil.ZHZT_DFP)) { // 01：通过的状态
            log.info("[ZhsqServiceImpl - updatePcZhzt]--------------- PC端自评审批 - 自评审批已通过");
            log.info("[ZhsqServiceImpl - updatePcZhzt]--------------- PC端自评审批 - 修改照护状态 - 01");
            zhsqRepository.updateZhzt(zt, id);
            zhsqHistory.setResult("通过");
            content.put("keyword3","自评审批已通过");
        } else {
            log.info("[ZhsqServiceImpl - updatePcZhzt]--------------- PC端自评审批 - 自评审批未通过");
            log.info("[ZhsqServiceImpl - updatePcZhzt]--------------- PC端自评审批 - 修改照护状态 - 00");
            zhsqRepository.updateZhzt(zt, id);
            zhsqHistory.setResult("未通过");
            zhsqHistory.setBz(bz);
            content.put("keyword3","自评审批未通过");
        }
        content.put("remark","请通过公众号查看。");
        msg.setContent(content.toJSONString());
        if(!StringUtils.isEmpty(msg.getTarget())){
            log.info("[ZhsqServiceImpl - updatePcZhzt]--------------- PC端自评审批 - 发送给申请人照护申请的节点状态");
            mpMsgService.create(msg);
        }
        log.info("[ZhsqServiceImpl - updatePcZhzt]--------------- PC端自评审批 - 记录照护审核日志");
        zhsqHistoryRepository.save(zhsqHistory);
        fpryRepository.updateFpryZt(id);
        log.info("[ZhsqServiceImpl - updatePcZhzt]--------------- PC端自评审批 end");
    }

    /**
     * PC端复核（包括居家和机构）
     * @param zt
     * @param id
     * @param bz
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZhsqDto updateFhZhzt(String zt, Long id, String bz) {
        log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 start");

        ZhsqDto zhsqDto = findById(id);

        if("03".equals(zhsqDto.getBisZhsqZhlb())) { // 居家照护
            log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 居家照护");
            Zhsq zhsq = zhsqRepository.findById(id).get();
            Long userId = zhsq.getBisUserId();
            UserDto user = userService.findById(userId);

            Msg msg = new Msg();
            msg.setType("WxTemplate");
            msg.setTimes(0);
            msg.setStatus("0");
            msg.setSendTime(new Timestamp(System.currentTimeMillis()));
            msg.setTarget(user.getWxOpenId());
            JSONObject content = new JSONObject();
            content.put("first","尊敬的用户，您提交的待遇申请有新的状态变动。");
            content.put("keyword1",zhsq.getBisZhsqSnryXm());
            content.put("keyword2",DateTimeUtil.getDateTime(zhsq.getLrsj(), "YYYY年MM月dd日"));

            ZhsqHistory zhsqHistory = new ZhsqHistory();
            zhsqHistory.setId(IdUtil.simpleUUID());
            zhsqHistory.setUserId(SecurityUtils.getCurrentUserId());
            zhsqHistory.setZhsqId(id);
            // 当前的状态
            zhsqHistory.setType(DefaultUtil.ZHZT_YZX);  // 04：已执行（已评估）
            if("00".equals(zt)) {
                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 复核未通过");
                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 修改照护状态 - 01");
                zhsqRepository.updateZhzt(DefaultUtil.ZHZT_DFP, id);
                zhsqHistory.setResult("未通过");
                zhsqHistory.setBz(bz);
                content.put("keyword3","复核未通过");

                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 恢复评估人员复核状态");
                fpryRepository.updateResumeFpryZt(id);
            } else {
                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 复核已通过");
                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 修改照护状态 - 06");
                zhsqRepository.updateZhzt(DefaultUtil.ZHZT_GSZ, id);
                zhsqHistory.setResult("通过");
                content.put("keyword3","复核已通过");

                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 发布公示");
                Gs gs = new Gs();
                gs.setBisGsId(IdUtil.simpleUUID());
                gs.setBisGsBt(zhsqDto.getBisZhsqSnryXm());
                gs.setBisGsNr(zhsqDto.getBisZhsqSnrySfz().substring(0,6)+"********"+zhsqDto.getBisZhsqSnrySfz().substring(14));
                gs.setBisGsZhid(zhsqDto.getBisZhsqId());
                gs.setBisGsZt("0");
                gs.setBisGsRq(DateTimeUtil.getDate());
                gs.setBisGsFbr(String.valueOf(SecurityUtils.getCurrentUserId()));
                gsRepository.save(gs);
            }

            content.put("remark","请通过公众号查看。");
            msg.setContent(content.toJSONString());
            if(!StringUtils.isEmpty(msg.getTarget())){
                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 发送给申请人照护申请的节点状态");
                mpMsgService.create(msg);
            }

            log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 记录照护审核日志");
            zhsqHistoryRepository.save(zhsqHistory);
        } else { // 机构照护
            log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 机构照护");


            ZhsqHistory zhsqHistory = new ZhsqHistory();
            zhsqHistory.setId(IdUtil.simpleUUID());
            zhsqHistory.setUserId(SecurityUtils.getCurrentUserId());
            zhsqHistory.setZhsqId(id);
            // 当前的状态
            zhsqHistory.setType(DefaultUtil.ZHZT_YZX);  // 04：已执行（已评估）
            if("00".equals(zt)) {
                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 复核未通过");
                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 修改照护状态 - 01");
                zhsqRepository.updateZhzt(DefaultUtil.ZHZT_DFP, id);
                zhsqHistory.setResult("未通过");
                zhsqHistory.setBz(bz);

                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 恢复评估人员复核状态");
                fpryRepository.updateResumeFpryZt(id);
            } else {
                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 机构照护申请 - 复核 - 开始 zhid:{}", id);
                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 机构照护申请 - 执行2901");

                StoredProcedureQuery storedProcedureQuery = this.em.createNamedStoredProcedureQuery("make2901");

                storedProcedureQuery.setParameter("IR_USER_ID", String.valueOf(SecurityUtils.getCurrentUserId()));
                storedProcedureQuery.setParameter("IR_ZHID", String.valueOf(id));

                storedProcedureQuery.execute();
                int code = (int) storedProcedureQuery.getOutputParameterValue("OR_APPCODE");
                String msg = (String) storedProcedureQuery.getOutputParameterValue("OR_MESSAGE");

                log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 机构照护申请 - 复核 - 结束 :code:{}，msg:{}", code, msg);
                String[] msgArray = msg.split("\\|");
                if(code == 1) {
                    log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 复核已通过");
                    log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 修改照护状态 - 05");
                    zhsqRepository.updateZhzt(DefaultUtil.ZHZT_YRD, id);
                    zhsqRepository.updateSpbh(msgArray[1], id);
                    zhsqHistory.setResult("通过");
                } else {
                    throw new BadRequestException(msg);
                }
            }

            log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 - 记录照护审核日志");
            zhsqHistoryRepository.save(zhsqHistory);
        }
        log.info("[ZhsqServiceImpl - updateFhZhzt]--------------- PC端复核 end");
        return zhsqDto;
    }


    /**
     * 经办中心PC端评估照护
     * @param zt
     * @param id
     * @param bz
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkPgPcjgzh(String zt, Long id,String bz, Zhsq resources) {
        log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 start");
        // 更新分配人员表的完成状态
        log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 更新分配人员表的完成状态");

        Long userid = SecurityUtils.getCurrentUserId();
        String username  = SecurityUtils.getCurrentNickName();
        // fpryRepository.updateFpryWczt(id, DefaultUtil.RYLX_PGRY);
        fpryRepository.updateFpryZt(id);

        Zhsq zhsq = zhsqRepository.findById(id).get();
        Date lrsj = zhsq.getBisZhsqTjsj();

        ZhsqHistory zhsqHistory = new ZhsqHistory();
        zhsqHistory.setId(IdUtil.simpleUUID());
        zhsqHistory.setUserId(SecurityUtils.getCurrentUserId());
        zhsqHistory.setZhsqId(id);
        zhsqHistory.setType("02");
        zhsqHistory.setBz(bz);

        if(zt.equals("54")) {
            // 先获取实体中的ADL量表信息
            List<AdlZhsq> list = resources.getAdlZhsqs();
/*
            String[] adlIds = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                AdlZhsq adl = list.get(i);
                adlIds[i] = adl.getAdlXmxxId();
            }
            String fs = adlZhsqRepository.queryScore(adlIds);
            // adl量表自评分数
            zhsq.setBisZhsqAdl(fs);
*/
/*

            for (int i = 0; i < list.size(); i++) {
                AdlZhsq adl = list.get(i);
                adl.setBisAdlZhsqId(IdUtil.simpleUUID());
                adl.setZhsq(zhsq);
                adl.setBisUserId(SecurityUtils.getCurrentUserId());
                adl.setYwlx("RYLX02");
                adlZhsqRepository.save(adl);
            }

            String c1 = adlZhsqRepository.queryC1(zhsq.getBisZhsqId());
            String c2 = adlZhsqRepository.queryC2(zhsq.getBisZhsqId());
            String c3 = adlZhsqRepository.queryC3(zhsq.getBisZhsqId());
            String lastFs = c1+"/"+c2+"/"+c3;
            // adl量表自评分数
            zhsq.setBisZhsqAdl(lastFs);
            log.info("[ZhsqServiceImpl - updateZhzt]--------------- 手机端评估机构照护 - 保存ADL量表评分 - {}", lastFs);

            Map<String, String> snMap = GetSndj.analyse(Integer.parseInt(c1),Integer.parseInt(c2),Integer.parseInt(c3), Integer.parseInt(zhsq.getBisZhsqNl()));

*/
            String sndj = "";
            String dyqx = "";
            if(Integer.parseInt(zhsq.getBisZhsqNl()) >= 90) {
                sndj = "90周岁以上";
                dyqx = "6";
            } else if (Integer.parseInt(zhsq.getBisZhsqNl()) >= 85 && Integer.parseInt(zhsq.getBisZhsqNl()) < 90) {
                sndj = "85周岁以上";
                dyqx = "12";
            }

            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 失能等级 - {}", sndj);
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 待遇期限 - {}", dyqx + "个月");
            zhsq.setBisZhsqSndj(sndj);
            Date dykkrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(lrsj, DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
            if("85周岁以上".equals(sndj) || "90周岁以上".equals(sndj)) {

                int month = DateTimeUtil.getMonth(lrsj);
                Date dyjsrq = null;

                if(month >= 10) {
                    log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 申请月份为 {}", month);
                    log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 85周岁以上，待遇期为第二年最后一天");
                    dyjsrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateUtil.endOfYear(DateTimeUtil.addMonths(lrsj, 12)), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);

                } else {
                    log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 申请月份为 {}", month);
                    log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 85周岁以上，待遇期为年末最后一天");
                    dyjsrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateUtil.endOfYear(lrsj), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);

                }
                log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 待遇开始日期：{}，待遇结束日期：{} ", dyjsrq, dyjsrq);
                int months = DateTimeUtil.diffMonths(dyjsrq, dykkrq);
                months = months == 0 ? 1 : months;
                zhsq.setBisZhsqDykkrq(dykkrq);
                zhsq.setBisZhsqDyjsrq(dyjsrq);
                zhsq.setBisZhsqXsdyq(months+"个月");
            } else {
                Date tempDate = DateTimeUtil.addMonths(dykkrq, Integer.parseInt(dyqx));
                Date dyjsrq = DateTimeUtil.addDays(tempDate, -1);
                log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 待遇开始日期：{}，待遇结束日期：{} ", dyjsrq, dyjsrq);
                zhsq.setBisZhsqDykkrq(dykkrq);
                zhsq.setBisZhsqDyjsrq(dyjsrq);
                zhsq.setBisZhsqXsdyq(dyqx+"个月");
            }
            this.update(zhsq);

            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 评估已通过");
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 修改照护状态 - 54");
            zhsqRepository.updateZhzt("55", id);
            zhsqHistory.setResult("通过");
            zhsqHistory.setBz(bz);
/*
            if("220101".equals(zhsq.getBisZhsqSnryYbssqx())) {
            }*/
            Gsgl gsgl = gsglRepository.findByBisGsglYljgdm(zhsq.getBisZhsqHljgBm());
            if("'220102','220103','220104','220105','220106','220107','220108','220109','220110', '220176', '220199'".indexOf(gsgl.getBisGsglSsqx())!=-1) {
                List<OrgWeightVo> listWeight = userService.queryUserWeight(220101l, "55");
                int prizeIndex = WeightUtil.getOrgWeigth(listWeight);
                OrgWeightVo prizeDto = listWeight.get(prizeIndex);
                Long userId = prizeDto.getId();
                String userName = prizeDto.getName();
                log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 随机分配 - 复核人员ID {}，复核人员姓名 {} ", userId, userName);

                Fpry fpry = new Fpry();
                fpry.setBisFpryId(IdUtil.simpleUUID());
                fpry.setBisFpryZhsqId(zhsq.getBisZhsqId());
                fpry.setBisFpryRyglId(userId);
                fpry.setBisFpryRyglXm(userName);
                fpry.setBisFpryFpsj(new Date());
                fpry.setBisFpryZt("0");
                fpryRepository.save(fpry);
            }

            // 双阳区和九台区管理的机构，需要中心人员复核
/*            Gsgl gsgl = gsglRepository.findByBisGsglYljgdm(zhsq.getBisZhsqHljgBm());
            if("220181".equals(gsgl.getBisGsglYbqh()) || "220112".equals(gsgl.getBisGsglYbqh())) {
                List<OrgWeightVo> listWeight = userService.queryUserWeight(999999l, "55");
                int prizeIndex = WeightUtil.getOrgWeigth(listWeight);
                OrgWeightVo prizeDto = listWeight.get(prizeIndex);
                Long userId = prizeDto.getId();
                String userName = prizeDto.getName();
                log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 随机分配 - 复核人员ID {}，复核人员姓名 {} ", userId, userName);

                Fpry fpry = new Fpry();
                fpry.setBisFpryId(IdUtil.simpleUUID());
                fpry.setBisFpryZhsqId(zhsq.getBisZhsqId());
                fpry.setBisFpryRyglId(userId);
                fpry.setBisFpryRyglXm(userName);
                fpry.setBisFpryFpsj(new Date());
                fpry.setBisFpryZt("0");
                fpryRepository.save(fpry);
            }*/
        }else if(zt.equals("80")) {
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 评估退回");
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 修改照护状态 - 80");
            zhsqRepository.updateZhzt("80", id);
            zhsqHistory.setResult("退回");
            zhsqHistory.setBz(bz);
        }else if(zt.equals("60")) {
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 抽取通过");
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 调整存疑状态 - 60");
            zhsqCyRepository.updateZhzt("60", userid, username, id);
            zhsqHistory.setType("06"); // 抽取状态
            zhsqHistory.setResult("通过");
            zhsqHistory.setBz(bz);
        }else if(zt.equals("61")) {
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 抽取存疑");
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 调整存疑状态 - 61");
            zhsqCyRepository.updateZhzt("61", userid, username, id);
            zhsqHistory.setType("06"); // 抽取状态
            zhsqHistory.setResult("未通过");
            zhsqHistory.setBz(bz);
        }else if(zt.equals("62")) {
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 存疑通过");
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 不调整状态");
            zhsqHistory.setType("08"); // 存疑状态
            zhsqHistory.setResult("通过");
            zhsqHistory.setBz(bz);
        }else if(zt.equals("63")) {
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 存疑终止");
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 修改照护状态 - 90");
            zhsqRepository.updateZhzt1("90", id);
            zhsqHistory.setType("08"); // 存疑状态
            zhsqHistory.setResult("未通过");
            zhsqHistory.setBz(bz);
        } else {
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 评估未通过");
            log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 修改照护状态 - -4");
            zhsqRepository.updateZhzt("-4", id);
            zhsqHistory.setResult("未通过");
            zhsqHistory.setBz(bz);
        }

        log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 - 记录照护审核日志");
        zhsqHistoryRepository.save(zhsqHistory);
        log.info("[ZhsqServiceImpl - checkPgPcjgzh]--------------- 经办中心PC端评估照护 end");
    }

    /**
     * 经办中心PC端复核照护申请
     * @param zt
     * @param id
     * @param bz
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkJbzxZhsq(String zt, Long id, String bz, Zhsq resources) {
        log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 start");
        // 更新分配人员表的完成状态
        log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 更新分配人员表的完成状态");
        // fpryRepository.updateFpryWczt(id, DefaultUtil.RYLX_PGRY);
        fpryRepository.updateFpryZt(id);

        Zhsq zhsq = zhsqRepository.findById(id).get();
        Date lrsj = zhsq.getBisZhsqTjsj();

        ZhsqHistory zhsqHistory = new ZhsqHistory();
        zhsqHistory.setId(IdUtil.simpleUUID());
        zhsqHistory.setUserId(SecurityUtils.getCurrentUserId());
        zhsqHistory.setZhsqId(id);
        // 当前的状态
        zhsqHistory.setType("04");  // 04：已执行（已评估）

        if(zt.equals("05")){

            // 先获取实体中的ADL量表信息
/*
            List<AdlZhsq> list = resources.getAdlZhsqs();
            String[] adlIds = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                AdlZhsq adl = list.get(i);
                adlIds[i] = adl.getAdlXmxxId();
            }
            String fs = adlZhsqRepository.queryScore(adlIds);
            // adl量表自评分数
            zhsq.setBisZhsqAdl(fs);
            log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 保存ADL量表评分 - {}", fs);


            Map<String, String> snMap = GetSndj.analyse(Integer.parseInt(fs), Integer.parseInt(zhsq.getBisZhsqNl()));
*/


            String sndj = "";
            String dyqx = "";
            if(Integer.parseInt(zhsq.getBisZhsqNl()) >= 90) {
                sndj = "90周岁以上";
                dyqx = "6";
            } else if (Integer.parseInt(zhsq.getBisZhsqNl()) >= 85 && Integer.parseInt(zhsq.getBisZhsqNl()) < 90) {
                sndj = "85周岁以上";
                dyqx = "12";
            }

            log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 失能等级 - {}", sndj);
            zhsq.setBisZhsqSndj(sndj);
            Date dykkrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(lrsj, DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);
            if("85周岁以上".equals(sndj) || "90周岁以上".equals(sndj)) {

                int month = DateTimeUtil.getMonth(lrsj);
                Date dyjsrq = null;

                if(month >= 10) {
                    log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 申请月份为 {}", month);
                    log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 85周岁以上，待遇期为第二年最后一天");
                    dyjsrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateUtil.endOfYear(DateTimeUtil.addMonths(lrsj, 12)), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);

                } else {
                    log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 申请月份为 {}", month);
                    log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 85周岁以上，待遇期为年末最后一天");
                    dyjsrq = DateTimeUtil.parse(DateTimeUtil.getDateTime(DateUtil.endOfYear(lrsj), DateTimeUtil.DEFAULT_DATE_FORMAT), DateTimeUtil.DEFAULT_DATE_FORMAT);

                }

                log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 待遇开始日期：{}，待遇结束日期：{} ", dykkrq, dyjsrq);
                int months = DateTimeUtil.diffMonths(dyjsrq, dykkrq);
                months = months == 0 ? 1 : months;
                zhsq.setBisZhsqDykkrq(dykkrq);
                zhsq.setBisZhsqDyjsrq(dyjsrq);
                zhsq.setBisZhsqXsdyq(months+"个月");
                log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 待遇期限 - {}", months + "个月");
            } else {
                Date tempDate = DateTimeUtil.addMonths(dykkrq, Integer.parseInt(dyqx));
                Date dyjsrq = DateTimeUtil.addDays(tempDate, -1);
                log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 待遇开始日期：{}，待遇结束日期：{} ", dykkrq, dyjsrq);
                zhsq.setBisZhsqDykkrq(dykkrq);
                zhsq.setBisZhsqDyjsrq(dyjsrq);
                zhsq.setBisZhsqXsdyq(dyqx+"个月");
                log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 待遇期限 - {}", dyqx + "个月");
            }
            this.update(zhsq);
/*

            for (int i = 0; i < list.size(); i++) {
                AdlZhsq adl = list.get(i);
                adl.setBisAdlZhsqId(IdUtil.simpleUUID());
                adl.setZhsq(zhsq);
                adl.setBisUserId(SecurityUtils.getCurrentUserId());
                adl.setYwlx("RYLX02");
                adlZhsqRepository.save(adl);
            }
*/

            log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 复核已通过");
            log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 修改照护状态 - 05");
            zhsqRepository.updateZhzt("05", id);
            zhsqHistory.setResult("通过");
        }else if(zt.equals("80")) {
            log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 复核退回");
            log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 修改照护状态 - 80");
            zhsqRepository.updateZhzt("80", id);
            zhsqHistory.setResult("退回");
            zhsqHistory.setBz(bz);
            log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - ADL结果作废");
            adlZhsqRepository.updateBisZfbs(id);
        } else {
            log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 复核未通过");
            log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 修改照护状态 - -5");
            zhsqRepository.updateZhzt("-5", id);
            zhsqHistory.setResult("未通过");
            zhsqHistory.setBz(bz);
            log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - ADL结果作废");
            adlZhsqRepository.updateBisZfbs(id);
        }

        log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 - 记录照护审核日志");
        zhsqHistoryRepository.save(zhsqHistory);
        log.info("[ZhsqServiceImpl - checkJbzxZhsq]--------------- 经办中心PC端复核 end");
    }

    @Override
    @Transactional
    public void cancelZhsq(String cause, Long id) {
        zhsqRepository.cancelZhsq(cause, id);
    }

    @Override
    @Transactional
    public void update(String tjrq, Long id) {
        zhsqRepository.update(tjrq, id);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long bisZhsqId : ids) {
            zhsqRepository.deleteById(bisZhsqId);
        }
    }

    @Override
    public void download(List<ZhsqDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ZhsqDto zhsq : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void downloadComplete(List<ZhsqDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ZhsqDto project : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("申请状态", project.getBisZhsqGrbh());
            map.put("姓名", project.getBisZhsqSnryXm());
            map.put("医保卡号", project.getBisZhsqYbkh());
            map.put("性别", project.getBisZhsqSnryXb());
            map.put("身份证", project.getBisZhsqSnrySfz());
            map.put("年龄", project.getBisZhsqNl());
            map.put("联系电话", project.getBisZhsqLxdh());
            map.put("监护人姓名", project.getBisZhsqJhrxm());
            map.put("监护人电话", project.getBisZhsqJhrdh());
            map.put("关系", project.getBisZhsqGx());
            map.put("医保所属区县", project.getBisZhsqSnryYbssqx());
            map.put("待遇开始日期", project.getBisZhsqDykkrq());
            map.put("待遇结束日期", project.getBisZhsqDyjsrq());
            map.put("享受待遇期", project.getBisZhsqXsdyq());
            map.put("ADL评分", project.getBisZhsqAdl());
            map.put("地址", project.getBisZhsqHldz());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void downloadZpbhList(List<ZhgkZpbhVo> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ZhgkZpbhVo project : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("姓名", project.getBisZhsqSnryXm());
            map.put("医保卡号", project.getBisZhsqYbkh());
            map.put("性别", project.getBisZhsqSnryXb());
            map.put("身份证", project.getBisZhsqSnrySfz());
            map.put("年龄", project.getBisZhsqNl());
            map.put("联系电话", project.getBisZhsqLxdh());
            map.put("监护人姓名", project.getBisZhsqJhrxm());
            map.put("监护人电话", project.getBisZhsqJhrdh());
            map.put("关系", project.getBisZhsqGx());
            map.put("失能老人所属区县", project.getBisZhsqHldzSsqx());
            map.put("医保所属区县", project.getBisZhsqSnryYbssqx());
            map.put("申请时间", DateTimeUtil.getDateTime(project.getLrsj(), DateTimeUtil.DEFAULT_DATETIME_FORMAT));
            map.put("自评审批时间", DateTimeUtil.getDateTime(project.getZpspTime(), DateTimeUtil.DEFAULT_DATETIME_FORMAT));
            map.put("自评审批人", project.getZpspr());
            map.put("自评审批意见", project.getZpspYj());
            map.put("地址", project.getBisZhsqHldz());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void downloadHomeApprove(List<ZhsqDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ZhsqDto project : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("申请时间", DateTimeUtil.getDateTime(project.getLrsj(), DateTimeUtil.DEFAULT_DATETIME_FORMAT));
            map.put("姓名", project.getBisZhsqSnryXm());
            map.put("医保卡号", project.getBisZhsqYbkh());
            map.put("性别", project.getBisZhsqSnryXb());
            map.put("身份证", project.getBisZhsqSnrySfz());
            map.put("年龄", project.getBisZhsqNl());
            map.put("联系电话", project.getBisZhsqLxdh());
            map.put("监护人姓名", project.getBisZhsqJhrxm());
            map.put("监护人电话", project.getBisZhsqJhrdh());
            map.put("关系", StringUtils.isEmpty(project.getBisZhsqGx()) ? "" : dictDetailService.findDictDetail(325l, project.getBisZhsqGx()).getLabel() );
            map.put("护理地址所属区", StringUtils.isEmpty(project.getBisZhsqHldzSsqx()) ? "" : dictDetailService.findDictDetail(251l, project.getBisZhsqHldzSsqx()).getLabel());
            map.put("地址", project.getBisZhsqHldz());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public ZhsqDto queryZhid(String bisZhsqSnrySfz, String hljgbm) {
        return zhsqMapper.toDto(zhsqRepository.queryZhid(bisZhsqSnrySfz, hljgbm));
    }

    @Override
    public ZhsqDto queryBySfz(String bisZhsqSnrySfz) {
        return zhsqMapper.toDto(zhsqRepository.queryBySfz(bisZhsqSnrySfz));
    }

    @Override
    public Map<String, Object> queryZpbhList(String blurry, String area, String sbgsId, Pageable pageable) {
        Page<ZhgkZpbhVo> page =  zhsqRepository.queryZpbhList(blurry, area, sbgsId, pageable);
        return PageUtil.toPage(page);
    }

    @Override
    public List<ZhgkZpbhVo> queryZpbhList(String blurry, String area, String sbgsId) {
        List<ZhgkZpbhVo> list = zhsqRepository.queryZpbhList(blurry, area, sbgsId);
        return list;
    }

    @Override
    public Object updateById(String orderId) {
        try {
            Optional<Order> byId = orderRepository.findById(orderId);
            Order order = byId.get();
            order.setBisOrderXjzt("2");
            Order save = orderRepository.save(order);
            return save;
        } catch (Exception e){
            return e;
        }
    }

    @Override
    public Integer calculateOrgDelayDays(Long zhid) {
        return zhsqRepository.calculateOrgDelayDays(zhid);
    }

    @Override
    public String getFpTargetDate(Long zhid) {
        return zhsqRepository.getFpTargetDate(zhid);
    }

    @Override
    public List<Map<String, Object>> getPdfScore(String zhsqId) {
        return zhsqRepository.getPdfScore(zhsqId);
    }
}
